<template>
  <a-modal
    title="查询区域信息"
    width="80%"
    :visible="areaVisible"
    :confirm-loading="areaConfirmLoading"
    :closable="false"
    @ok="areaHandleOk"
    @cancel="areaHandleCancel"
  >
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row >
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="区域名称"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-input v-model="areaQueryParams.areaName"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="创建时间"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <range-date @change="handleDateChange" ref="createTime"></range-date>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button type="primary" @click="searchArea">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetArea">重置</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <!-- 表格区域 -->
      <a-table ref="AreaTableInfo"
               rowKey="id"
               :columns="areaColumns"
               :dataSource="areaDataSource"
               :pagination="areaPagination"
               :loading="arealoading"
               :rowSelection="{selectedRowKeys: selectedAreaRowKeys, onChange: onSelectChange}"
               @change="handleAreaTableChange" :scroll="{ x: 1500 }">
        <template v-if="text" slot="icon" slot-scope="text, record">
          <a-icon :type="text" />
        </template>
      </a-table>
    </div>
  </a-modal>
</template>
<script>
import RangeDate from '@/components/datetime/RangeDate'

export default {
  name: 'AreaSearch',
  props: {
    areaVisible: {
      default: false
    }
  },
  components: {RangeDate},
  data () {
    return {
      advanced: false,
      form: this.$form.createForm(this),
      key: +new Date(),
      areaConfirmLoading: false,
      areaQueryParams: [],
      areaPaginationInfo: null,
      areaPagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      arealoading: false,
      areaDataSource: [],
      selectedAreaRowKeys: []
    }
  },
  computed: {
    areaColumns () {
        return [{
        title: '名称',
        dataIndex: 'text',
        key: 'id',
        width: 200,
        align: 'center',
        fixed: 'left'
      }, {
        title: '层级',
        dataIndex: 'value',
        width: 100,
        align: 'center'
      }, {
        title: '区域管理员',
        dataIndex: 'residents[0].rsName', // TODO 记得要修改字段
        width: 100,
        align: 'center'
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 200,
        align: 'center'
      }, {
        title: '修改时间',
        dataIndex: 'modifyTime',
        width: 200,
        align: 'center'
      }, {
        title: '操作',
        dataIndex: 'operation',
        width: 120,
        scopedSlots: {customRender: 'operation'},
        fixed: 'right'
      }]
    }
  },
  methods: {
    handleDateChange (value) {
      if (value) {
        this.areaQueryParams.createTimeFrom = value[0]
        this.areaQueryParams.createTimeTo = value[1]
      }
    },
    areaHandleOk (e) {
      this.resetArea()
      let retData = this.selectedRows ? this.selectedRows[0] : {}
      // this.areaDataSource.forEach(_key => { if (_key.id === this.selectedAreaRowKeys[0]) { retData = _key } })
      this.$emit('success', retData)
    },
    areaHandleCancel (e) {
      this.resetArea()
      this.$emit('close')
    },
    searchArea () {
      this.areaFetch({
          ...this.areaQueryParams
      })
    },
    resetArea () {
      // 重置分页
      this.$refs.AreaTableInfo.pagination.current = this.areaPagination.defaultCurrent
      if (this.areaPaginationInfo) {
          this.areaPaginationInfo.current = this.areaPagination.defaultCurrent
          this.areaPaginationInfo.pageSize = this.areaPagination.defaultPageSize
      }
      // 重置查询参数
      this.areaQueryParams = {}
      this.arealoading = false
      this.form.resetFields()
    },
    handleAreaTableChange (pagination) {
        // 将这两个参数赋值给Vue data，用于后续使用
        this.areaPaginationInfo = pagination
        this.areaFetch({
            ...this.areaQueryParams
        })
    },
    areaFetch (params = {}) {
        if (this.areaPaginationInfo) {
            // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
            this.$refs.AreaTableInfo.pagination.current = this.areaPaginationInfo.current
            this.$refs.AreaTableInfo.pagination.pageSize = this.areaPaginationInfo.pageSize
            params.pageSize = this.areaPaginationInfo.pageSize
            params.pageNum = this.areaPaginationInfo.current
        } else {
            // 如果分页信息为空，则设置为默认值
            params.pageSize = this.areaPagination.defaultPageSize
            params.pageNum = this.areaPagination.defaultCurrent
        }

        this.arealoading = true
        this.$get('tArea', {
            ...params
        }).then((r) => {
            let data = r.data
            const pagination = { ...this.areaPagination }
            pagination.total = data.total
            // this.areaDataSource = data.rows
            this.areaPagination = pagination
            this.arealoading = false
            if (Object.is(data.rows.children, undefined)) {
              this.areaDataSource = data.rows
            } else {
              this.areaDataSource = data.rows.children
            }
        })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedAreaRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
    }
  },
  watch: {
    areaVisible () {
      if (this.areaVisible) {
        this.selectedAreaRowKeys = []
          this.areaFetch({
              ...this.areaQueryParams
          })
      }
    }
  }
}
</script>
<style lang="less" scoped>
  @import "../../../../static/less/Common";
</style>
